package lv.solcraft.replication.server.rest.restlets;

import java.io.IOException;

import lv.solcraft.replication.server.api.ServerFacade;
import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.restlet.Context;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Resource;

public class OperRecieverResource extends Resource {
    
    private static final Logger log = Logger.getLogger(OperRecieverResource.class);

    private long siteId;

    private ServerFacade serverFacade;

    /** should be injected by Spring automatically */
    public void setServerFacade(ServerFacade serverFacade) {
        this.serverFacade = serverFacade;
    }

    public OperRecieverResource() {
        super();
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        siteId = Long.parseLong(request.getAttributes().get("site").toString());
    }

    @Override
    public boolean allowPost() {
        return true;
    }

    @Override
    public void handlePost() {
        try {
            String input = getRequest().getEntity().getText();
            JSONArray array = JSONArray.fromObject(input);
            if (log.isDebugEnabled()) {
                log.debug("Recieved opers: " + array.toString(1));
            }
            serverFacade.saveJSON(siteId, array);
        } catch (IOException e) {
            throw new IllegalStateException("Operation saving failed, " + e.getMessage(), e);
        }
    }
}
